package com.fosss.kmp;

import java.util.Arrays;

/**
 * kmp算法实现字符串匹配
 */

public class KmpAlgorithm {
    public static void main(String[] args) {
        String str1 = "BBC ABCDAB ABCDABCDABDE";
        String str2 = "ABCDABD";

//        int[] arr = next("ABCDABD");
//        System.out.println(Arrays.toString(arr));

        int index = kmpSearch(str1, str2);
        System.out.println(index);

    }

    /**
     * 实现kmp算法查找
     *
     * @param str1 文本串
     * @param str2 模式串
     * @return -1为没找到，找到则返回首索引
     */
    public static int kmpSearch(String str1, String str2) {
        //获取部分匹配值表
        int[] next = next(str2);

        for (int i = 0, j = 0; i < str1.length(); i++) {

            //kmp核心
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }

            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }

            if (j == str2.length()) {//如果j==字符串的长度，说明找到了，返回首索引
                return i - j + 1;
            }
        }
        //找不到，返回-1
        return -1;
    }

    /**
     * 得到部分匹配值表
     */
    public static int[] next(String dest) {
        int[] next = new int[dest.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < dest.length(); i++) {

            //2.
            while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
                j = next[j - 1];//kmp算法的核心
            }

            //1.
            if (dest.charAt(i) == dest.charAt(j)) {
                j++;
            }

            next[i] = j;
        }
        return next;
    }
}



























